BEGIN {
	printf("scenarioTime \tduration \thaggleTime \thaggleDelay \n");
	inf = 999999;
}

{
	scenarioTime = $2;			# time into the scenario that the link goes up
	expNum = $6;				# experiment
	duration = $8;				# connectionTime
	haggleDelay = $9;			# time until haggle discovers link
	haggleTime = scenarioTime + haggleDelay;

	nodeA = $3;
	nodeB = $4;
	
	if ((prevNodeA != nodeA) || (prevNodeB != nodeB) || (prevScenarioTime-scenarioTime > 500) || (scenarioTime-prevScenarioTime > 500)) {

		if (cnt > 0) {
			cntDiscovered=0;
			minDuration=inf;
			minHaggleDelay=inf;

			# calculate mean value
			for (e=0;e<cnt;e++) {
				sumScenarioTime += aScenarioTime[e];
				if (aDuration[e] < minDuration) minDuration = aDuration[e];
#				if (aHaggleDelay[e] < aDuration[e]) {
					cntDiscovered++;
					sumHaggleTime += aHaggleTime[e];
					if (aHaggleDelay[e] < minHaggleDelay) minHaggleDelay = aHaggleDelay[e];
#				}
			}
			meanScenarioTime = sumScenarioTime / cnt;
			if (cntDiscovered > 0) {
				meanHaggleTime = sumHaggleTime / cntDiscovered;
			}

			# sort the array (to get median)
			# brute force approach
			delete cScenarioTime;			# copy to make changes
			delete cHaggleTime;				# copy to make changes
			for (s=0;s<cnt;s++) {
				cScenarioTime[s] = aScenarioTime[s];
				cHaggleTime[s] = aHaggleTime[s];
			}
			delete sScenarioTime;			# sorted array
			delete sHaggleTime;				# sorted array
			for (s=0;s<cnt;s++) {
				minScenarioIdx = 0;
				minHaggleIdx = 0;
				for (e=1;e<cnt;e++) {
					if (cScenarioTime[e] < cScenarioTime[minScenarioIdx]) minScenarioIdx = e;
					if (cHaggleTime[e] < cHaggleTime[minHaggleIdx]) minHaggleIdx = e;
				}
				sScenarioTime[s] = cScenarioTime[minScenarioIdx];
				sHaggleTime[s] = cHaggleTime[minHaggleIdx];
				cScenarioTime[minScenarioIdx] = inf;
				cHaggleTime[minHaggleIdx] = inf;
			}			
			medianScenarioTime = sScenarioTime[0];
			medianHaggleTime = sHaggleTime[0];


			# print statistics
			for (e=0;e<cnt;e++) {
				printf("%0.2f \t%0.2f \t%0.2f \t%0.2f \n", 
					aScenarioTime[e] - medianScenarioTime, 
					aDuration[e] - minDuration,
					aHaggleTime[e] - medianHaggleTime,
#					(aHaggleDelay[e] < aDuration[e] ? aHaggleTime[e] - meanHaggleTime : "-"), 
					(aHaggleDelay[e] < aDuration[e] ? aHaggleDelay[e] : "-"));
			}
		}
	

		sumScenarioTime = 0;
		sumDuration = 0;
		sumHaggleTime = 0;
		sumHaggleDelay = 0;

		sumScenarioTimeVar = 0;
		sumDurationVar = 0;
		sumHaggleTimeVar = 0;
		sumHaggleDelayVar = 0;
	
		meanScenarioTime = 0;
		meanDuration = 0;
		meanHaggleTime = 0;
		meanHaggleDelay = 0;

		varScenarioTime = 0;
		varDuration = 0;
		varHaggleTime = 0;
		varHaggleDelay = 0;

		delete aScenarioTime;
		delete aDuration;
		delete aHaggleTime;
		delete aHaggleDelay;

		cnt = 0;
	}

	aScenarioTime[cnt] = scenarioTime;
	aDuration[cnt] = duration;
	aHaggleTime[cnt] = haggleTime;
	aHaggleDelay[cnt] = haggleDelay;

	cnt++;
	prevNodeA = nodeA;
	prevNodeB = nodeB;
	prevScenarioTime = scenarioTime;
}